using System.Collections.Generic;
using UnityEngine;

namespace Gj
{
    public class DataService : GameService
    {
        public static DataService single;
        private readonly Dictionary<byte, Dictionary<int, int>> map = new();
        private float otherLastTime;
        private DataObject[] others;
        private float playerLastTime;
        private DataObject[] players;
        private readonly float refreshTime = 2f;

        static DataService()
        {
            single = new DataService();
        }

        public int PlayerIdentity { get; set; }

        public void OnDestroy()
        {
            single = new DataService();
        }

        public void OnInit()
        {
        }

        public void OnUpdate()
        {
            
        }

        public DataObject[] GetPlayers()
        {
            if (Time.time - playerLastTime > refreshTime)
            {
                var list = new List<DataObject>();
                foreach (var i in ControlService.single.list)
                    if (i.GetIdentity() == PlayerIdentity)
                        list.Add(i);
                players = list.ToArray();
                if (players.Length > 0) playerLastTime = Time.time;
            }

            return players;
        }

        public DataObject[] GetOther()
        {
            if (Time.time - otherLastTime > refreshTime)
            {
                var list = new List<DataObject>();
                foreach (var i in ControlService.single.list)
                {
                    var identity = i.GetIdentity();
                    if (identity > 0 && identity != PlayerIdentity) list.Add(i);
                }

                others = list.ToArray();
                if (others.Length > 0) otherLastTime = Time.time;
            }

            return others;
        }

        public int GetIndex(byte type, int category)
        {
            if (map.ContainsKey(type) && map[type].ContainsKey(category))
                return map[type][category];
            return -1;
        }

        public void SetIndex(byte type, int category, int value)
        {
            if (!map.ContainsKey(type)) map[type] = new Dictionary<int, int>();
            map[type][category] = value;
        }
    }
}